// pages/detail/detail.js
import {
    httpRequest
} from "../../utils/request"
import {
    baseUrl
} from "../../static/url"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        bill_coding : "0",
        form : {},
        repairForm : {
            content :""
        },
        is_owner : false,
        is_repairer : false,
        is_fp : false, //是否已分配
        is_fx : false, //是否通过分享链接进入, 通过分享链接进入不判断是否单据拥有者
        originFiles: [
        ],
        autosize: {
            maxHeight: 120,
            minHeight: 20,
        },
        subfiles : [],
        gridConfig: {
            column: 4,
            width: 160,
            height: 160,
        },

        visible: false,
        showIndex: false,
        closeBtn: true,
        deleteBtn: false,
        images: [],
        initialIndex : "0",
        onloadd : false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('onLoad', this.data.onloadd)

        this.setData({
            bill_coding : options.bill_coding,
            onloadd : true
        })
        if(options.fx == 22){
            this.setData({
                is_fx : true
            })
        }
        this.getDeatail()
    },
    onShow(){
        console.log('onShow', this.data.onloadd)
        if(this.data.onloadd == false){
            this.getDeatail()
        }
    },
    onClose(){
        this.setData({
            showIndex: false,
            visible: false,
        })
    },
    onClick(e) {
        console.log(e)
        let img = []
        if(e.currentTarget.dataset.p == 'problem'){
           for(let k in this.data.form.files)
           {
               let v = this.data.form.files[k]
               img.push(v)
           }
        }else{
            for(let k in this.data.repairform.files)
            {
                let v = this.data.form.files[k]
                img.push(v)
            }
        }
        this.setData({
          images:img,
          showIndex: true,
          visible: true,
          initialIndex : e.currentTarget.dataset.pp.toString()
        });
      },
    inputchange(e) {
        let form = this.data.repairForm
        form[e.currentTarget.dataset.field] = e.detail.value
        this.setData({
            repairForm : form
        });
    },
    goAddress(e){
        console.log(e)
        let address = e.currentTarget.dataset.address
        address = address.split(',')
        wx.openLocation({
          latitude: parseFloat(address[1]),
          longitude: parseFloat(address[0]),
        })
    },
    createRepair(){
        // 提交检修结果
        let that = this
        if(this.data.subfiles.length  < 1){
            wx.showModal({
                title: '提示',
                content: '至少上传一张图片',
            })
            return false
        }
        let form = this.data.repairForm
        form.files = this.data.subfiles
        form.bill_coding = this.data.bill_coding
        httpRequest("repair/bill/repair", 'POST', form).then(r => {
            if(r.code == 200){
                wx.showModal({
                  title: '提示',
                  content: '单据完成',
                  complete: (res) => {
                      wx.switchTab({
                        url: '/pages/bill/bill',
                      })
                  }
                })
            }else{
                wx.showModal({
                  title: '提示',
                  content: r.msg,
                })
            }
        })

        console.log(this.data.originFiles)
    },
    getDeatail(){
        let that = this
        setTimeout(() => {
            this.setData({
                onloadd : false
            })
        }, 500)

        let requestForm = {
            bill_coding : that.data.bill_coding
        }
        httpRequest("repair/bill/detail", 'POST', requestForm).then(r =>{
            if(r.code != 200){
                wx.showToast({
                  title: '未找到单据',
                  icon: "error",
                  success(){
                      setTimeout(function(){
                        wx.switchTab({
                            url: '/pages/index/index',
                          })
                      }, 800)
                  },
                })
                return false
            }
            let data = r.data.data
            for(let k in data['files']){
                data['files'][k] = baseUrl + '/' + data['files'][k]
            }
            that.setData({
                form : data,
                is_owner : r.data.is_owner,
                is_repairer : r.data.is_repairer,
                is_fp : r.data.is_fp,
                onloadd :false,
            })
            // console.log(r.data)
            if(r.data.repair_form != false){
                r.data.repair_form.content = r.data.repair_form.repair_content
                let files = r.data.repair_form.repair_files
                for(let k in files){
                    files[k] = baseUrl + '/' + files[k]
                }
                r.data.repair_form.repair_files = files
                this.setData({
                    repairForm : r.data.repair_form
                })
                // console.log(r.data.repair_form)
            }
            if(r.data.is_fp == false && r.data.is_owner && this.data.is_fx == false){
                wx.showModal({
                  title: '提示',
                  content : "该单据还未分配检修员,请到检修单主页分配",
                  success(r){
                  }
                })
            }
            if(r.data.is_fp == false && ((r.data.is_owner == false && r.data.is_repairer == false) || (this.data.is_fx == true && r.data.is_repairer == false))){
                // 其他人进入页面 
                wx.showModal({
                    title :"提示",
                    content : "作为检修员接收本单据?",
                    cancelText : "暂不接收",
                    confirmText : "接收单据",
                    success(r){
                        if(r.confirm){
                            //绑定当前用户并刷新本单据
                            httpRequest("repair/bill/receive", 'POST', {
                                bill_coding : that.data.bill_coding,
                            }).then(r =>{
                                wx.showToast({
                                  title: '接收成功',
                                })
                                that.getDeatail()
                                // if(r.code != 200){}
                            })
                        }
                    },
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },


    handleFail(e){
        if(e.detail.errMsg == 'chooseMedia:fail cancel'){
            return false
        }
        const {
            originFiles
        } = this.data;
        const {
            length
        } = originFiles;
        this.setData({
            [`originFiles[${length}].status`]: 'fail',
        });
    },
    handleAdd(e) {
        // const { originFiles } = this.data;
        const {
            files
        } = e.detail;

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        // this.setData({
        //     originFiles: [...originFiles, ...files], // 此时设置了 fileList 之后才会展示选择的图片
        // });

        // 方法2：每次选择图片都上传，展示每次上传图片的进度
        files.forEach(file => this.onUpload(file))
    },
    onUpload(file) {
        console.log(file)
        let self = this

        var token = wx.getStorageSync('token')
        if (!token) {
            wx.showToast({
                title: '请先登录',
                icon: "none"
            })
            setTimeout((

            ) => {
                wx.navigateTo({
                    url: '/pages/login/login',
                })
            }, 800)
            return false
        }
        const {
            originFiles
        } = this.data;
        this.setData({
            originFiles: [...originFiles, {
                ...file,
                status: 'loading'
            }],
        });
        const {
            length
        } = originFiles;
        const task = wx.uploadFile({
            url: baseUrl + '/api/upload/upload?HTTP_TOKENs=' + token, // 
            filePath: file.url,
            name: 'file',
            formData: {
                user: 'test'
            },
            success: (r) => {
                if(r.statusCode != 200){
                    wx.showToast({
                      title: '上传失败,未知原因',
                      icon : "error"
                    })
                    self.setData({
                        [`originFiles[${length}].status`]: 'fail',
                    });
                    return false
                }
                console.log(r)
                let data = JSON.parse(r.data)
                let subfiles = self.data.subfiles
                subfiles.push(data.data.file_name)
                self.setData({
                    subfiles: subfiles,
                    [`originFiles[${length}].status`]: 'done',
                });
            },
            fail() {
                self.setData({
                    [`originFiles[${length}].status`]: 'fail',
                });
            }
        });
        task.onProgressUpdate((res) => {
            self.setData({
                [`originFiles[${length}].percent`]: res.progress,
            });
        });
    },
    handleSuccess(e) {
        const {
            files
        } = e.detail;
        // this.setData({
        //   originFiles: files,
        // });
    },
    handleRemove(e) {
        const {
            index
        } = e.detail;
        const {
            originFiles,
            subfiles
        } = this.data;
        originFiles.splice(index, 1);
        subfiles.splice(index, 1);
        this.setData({
            originFiles,
            subfiles
        });
    },
    handleClick(e) {
        console.log(e.detail.file);
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})